package com.novunda.platform.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.novunda.platform.common.exception.NovException;
import com.novunda.platform.common.reponse.CommonResponse;
import com.novunda.platform.common.utils.StringUtil;
import com.novunda.platform.common.web.controller.BaseController;
import com.novunda.platform.common.web.modal.Page;
import com.novunda.platform.entities.Log;
import com.novunda.platform.entities.ReportLog;
import com.novunda.platform.services.LogService;
import com.novunda.tca.tdk.utils.GsonUtils;

/**
 * .. 审计记录
 *
 * @author yangg
 * @since 2016/9/12.
 */
@Controller
@RequestMapping("/sys/log")
public class LogController extends BaseController {
	@Autowired
	private LogService logService;
	// 导出失败提示
	private static final String EXPORT_ERROR = "导出审计记录失败";

	/**
	 * 审计记录首页 --展示列表及提供搜索功能
	 *
	 * @param keyWord
	 *            查询关键字
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @param model
	 *            提示信息
	 * @return 审计信息列表页面
	 */
	@RequiresPermissions("sys:log:view")
	@RequestMapping({ "index", "" })
	public String index(String keyWord, HttpServletRequest request, HttpServletResponse response, Model model) {

		Page<Log> logPage = logService.find(new Page<Log>(request, response),
				StringUtil.isEmpty(keyWord) ? "" : keyWord.trim());

		model.addAttribute("logs", logPage);
		model.addAttribute("keyWord", keyWord);
		return "modules/conf/logs";
	}

	/**
	 * 导出审计记录
	 *
	 * @param startTime
	 *            导出查询开始时间
	 * @param endTime
	 *            导出查询截止时间
	 * @param response
	 *            响应
	 * @param model
	 *            提示
	 * @param redirectAttributes
	 *            重定向
	 */
	@RequiresPermissions("sys:log:export")
	@RequestMapping("export")
	public void export(Date startTime, Date endTime, HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		OutputStream out = null;
		InputStream in = null;
		try {
			response.setHeader("content-disposition",
					"attachment;filename=" + URLEncoder.encode("logs_report.pdf", "UTF-8"));
			in = logService.export(startTime, endTime);
			out = response.getOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (IOException e) {
			LOG.error(EXPORT_ERROR, e);
			addMessage(redirectAttributes, EXPORT_ERROR);

		} finally {
			try {
				if (out != null) {
					out.flush();
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				LOG.error(EXPORT_ERROR, e);
				addMessage(redirectAttributes, EXPORT_ERROR);
			}

		}
	}

	/**
	 * 日志上报
	 *
	 * @param log
	 *            日志对象
	 * @return 结果
	 */
	@RequestMapping("report")
	@ResponseBody
	public String report(ReportLog log) {
		CommonResponse response = new CommonResponse();
		try {
			logService.saveReport(log);
			response.setReturnCode(0);
			response.setReturnMessage("ok");
		} catch (NovException e) {
			response.setReturnCode(-1);
			response.setReturnMessage(e.getMessage());
		} catch (Exception e) {
			LOG.error("日志上报失败", e);
			response.setReturnCode(-1);
			response.setReturnMessage("error");
		}
		return GsonUtils.getInstance().toJson(response);
	}

	/**
	 * 清空审计记录
	 *
	 * @return 操作结果
	 */
	@RequiresPermissions("sys:log:delete")
	@RequestMapping("clear")
	public String clear() {
		logService.clear();
		return "redirect:" + "/sys/log";
	}

	/**
	 * 判断时间段内是否存在数据
	 *
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            截止时间
	 * @return 是否存在数据
	 */
	@RequestMapping("checkDate")
	@ResponseBody
	public String checkDate(Date startTime, Date endTime) {

		if (logService.dataExist(startTime, endTime)) {
			return "true";
		}
		return "false";

	}

}
